package com.whut.manage.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whut.manage.config.WebSocketConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import static com.whut.manage.utils.IotDevicesUtil.getDeviceStatusResponseBodyDataList;

@Component
@Slf4j
@ServerEndpoint(value = "/api/websocket/{sid}")
public class RealTimeDataUpdateWebSocket {

    private static int onlineCount=0;
    private static CopyOnWriteArraySet<RealTimeDataUpdateWebSocket> webSocketSet= new CopyOnWriteArraySet<>();
    private Session session;
    private String sid="";
    private String simName="";

//    @Autowired
    public static TSDBRealTimeUpdateService tsdbRealTimeUpdateService;

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid){
        this.session=session;
        simName = session.getQueryString() == null ? "" : session.getQueryString();
        webSocketSet.add(this);
        this.sid=sid;
        addOnlineCount();           //在线数加1
        try {
//            sendMessage("conn_success");
            if ("basicD81L".equals(this.sid)) {
                this.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("deviceName","hl30003016").toJSONString());
            }
            if ("productionD81L".equals(this.sid)){
                this.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("deviceName","hl30003016").toJSONString());
            }
            if ("qualityD81L".equals(this.sid)) {
                this.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("deviceName","hl30003016").toJSONString());
            }
            if ("waveD81L".equals(this.sid)) {
                this.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("deviceName","hl30003016").toJSONString());
            }
            if ("slubD81L".equals(this.sid)) {
                this.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("deviceName","hl30003016").toJSONString());
            }

            /*
             * TM19_1设备
             * */
            if ("basicTM19_1".equals(this.sid)) {
//                this.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("deviceName","HL30003017").toJSONString());
                this.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("name","HL30003017").toJSONString());
            }
            if ("productionTM19_1".equals(this.sid)){
//                this.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("deviceName","HL30003017").toJSONString());
                this.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("name","HL30003017").toJSONString());
            }
            if ("qualityTM19_1".equals(this.sid)) {
//                this.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("deviceName","HL30003017").toJSONString());
                this.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("name","HL30003017").toJSONString());
            }
            if ("waveTM19_1".equals(this.sid)) {
//                this.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("deviceName","HL30003017").toJSONString());
                this.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("name","HL30003017").toJSONString());
            }
            if ("slubTM19_1".equals(this.sid)) {
//                this.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("deviceName","HL30003017").toJSONString());
                this.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("name","HL30003017").toJSONString());
            }

            /*
             * TM19_2设备
             * */
            if ("basicTM19_2".equals(this.sid)) {
                this.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("deviceName","HL30003018").toJSONString());
            }
            if ("productionTM19_2".equals(this.sid)){
                this.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("deviceName","HL30003018").toJSONString());
            }
            if ("qualityTM19_2".equals(this.sid)) {
                this.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("deviceName","HL30003018").toJSONString());
            }
            if ("waveTM19_2".equals(this.sid)) {
                this.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("deviceName","HL30003018").toJSONString());
            }
            if ("slubTM19_2".equals(this.sid)) {
                this.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("deviceName","HL30003018").toJSONString());
            }

            /*
             * TM15 设备
             * */

            if ("basicTM15".equals(this.sid)) {
//                this.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("deviceName","HL30003019").toJSONString());
                this.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("name","HL30003019").toJSONString());

            }
            if ("productionTM15".equals(this.sid)){
//                this.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("deviceName","HL30003019").toJSONString());
                this.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("name","HL30003019").toJSONString());

            }
            if ("qualityTM15".equals(this.sid)) {
//                this.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("deviceName","HL30003019").toJSONString());
                this.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("name","HL30003019").toJSONString());

            }
            if ("waveTM15".equals(this.sid)) {
//                this.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("deviceName","HL30003019").toJSONString());
                this.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("name","HL30003019").toJSONString());

            }
            if ("slubTM15".equals(this.sid)) {
//                this.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("deviceName","HL30003019").toJSONString());
                this.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("name","HL30003019").toJSONString());

            }


            if("SimDeviceProduction".equals(this.sid)){
                this.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("name",simName).toString());
            }
            if("SimDeviceWave".equals(this.sid)){
                this.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("name",simName).toString());
            }
            if("SimDeviceSlub2H".equals(this.sid)){
                this.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("name",simName).toString());
            }
            if("SimDeviceBasic".equals(this.sid)){
                this.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("name",simName).toString());
            }
            if("SimDeviceQuality".equals(this.sid)){
                this.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("name",simName).toString());
            }
            if ("DeviceStatus".equals(this.sid)){
                this.sendMessage(JSON.toJSONString(getDeviceStatusResponseBodyDataList()));
            }

            log.info("有新窗口开始监听:" + sid + ",当前在线人数为:" + getOnlineCount());
            log.info("有连接加入，当前连接数{},连接的人为：{}",getOnlineCount(),sid);
        } catch (Exception e) {
            log.error("websocket IO Exception");
        }}

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        //断开连接情况下，更新主板占用情况为释放
        log.info("释放的sid为："+sid);
        //这里写你 释放的时候，要处理的业务
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());

    }

    /**
     * 收到客户端消息后调用的方法
     * @ Param message 客户端发送过来的消息
     */
//    @OnMessage
//    public void onMessage(String message, Session session) throws InterruptedException {
//        log.info("收到来自窗口" + sid + "的信息:" + message);
//        //群发消息
//        for (RealTimeDataUpdateWebSocket item : webSocketSet) {
//            try {
//                //加判断是那个模块todo
//                if (item.sid.equals("wr")){
//                item.sendMessage(message+"0");
//
//                }
////                Thread.sleep(1500);
//                if (item.sid.equals("wr1")){
//                    item.sendMessage(message+"1");}
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }
    @Scheduled(fixedRate = 10000)//代表毫秒，spring的计划
    public void pushData()  {
        for (RealTimeDataUpdateWebSocket item : webSocketSet) {
            try {

//                与收到的模块判断对应,新增质量模块在这里加
                /*
                * D81L设备
                * */
                if ("basicD81L".equals(item.sid)) {
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("deviceName","hl30003016").toJSONString());
                }
                if ("productionD81L".equals(item.sid)){
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("deviceName","hl30003016").toJSONString());
                }
                if ("qualityD81L".equals(item.sid)) {
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("deviceName","hl30003016").toJSONString());
                }
                if ("waveD81L".equals(item.sid)) {
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("deviceName","hl30003016").toJSONString());
                }
                if ("slubD81L".equals(item.sid)) {
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("deviceName","hl30003016").toJSONString());
                }

                /*
                * TM19_1设备
                * */
                if ("basicTM19_1".equals(item.sid)) {
//                    item.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("deviceName","HL30003017").toJSONString());
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("name","HL30003017").toJSONString());
                }
                if ("productionTM19_1".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("deviceName","HL30003017").toJSONString());
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("name","HL30003017").toJSONString());
                }
                if ("qualityTM19_1".equals(item.sid)) {
//                    item.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("deviceName","HL30003017").toJSONString());
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("name","HL30003017").toJSONString());
                }
                if ("waveTM19_1".equals(item.sid)) {
//                    item.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("deviceName","HL30003017").toJSONString());
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("name","HL30003017").toJSONString());
                }
                if ("slubTM19_1".equals(item.sid)) {
//                    item.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("deviceName","HL30003017").toJSONString());
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("name","HL30003017").toJSONString());
                }

                /*
                * TM19_2设备
                * */
                if ("basicTM19_2".equals(item.sid)) {
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("deviceName","HL30003018").toJSONString());
                }
                if ("productionTM19_2".equals(item.sid)){
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("deviceName","HL30003018").toJSONString());
                }
                if ("qualityTM19_2".equals(item.sid)) {
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("deviceName","HL30003018").toJSONString());
                }
                if ("waveTM19_2".equals(item.sid)) {
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("deviceName","HL30003018").toJSONString());
                }
                if ("slubTM19_2".equals(item.sid)) {
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("deviceName","HL30003018").toJSONString());
                }

                /*
                * TM15 设备
                * */

                if ("basicTM15".equals(item.sid)) {
//                    item.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("deviceName","HL30003019").toJSONString());
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("name","HL30003019").toJSONString());
                }
                if ("productionTM15".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("deviceName","HL30003019").toJSONString());
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("name","HL30003019").toJSONString());
                }
                if ("qualityTM15".equals(item.sid)) {
//                    item.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("deviceName","HL30003019").toJSONString());
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("name","HL30003019").toJSONString());
                }
                if ("waveTM15".equals(item.sid)) {
//                    item.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("deviceName","HL30003019").toJSONString());
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("name","HL30003019").toJSONString());
                }
                if ("slubTM15".equals(item.sid)) {
//                    item.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("deviceName","HL30003019").toJSONString());
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("name","HL30003019").toJSONString());
                }

                //模拟设备计划推送

                //查询模拟设备的基础信息(tag=name)
//                if("SimDeviceBasic4GGW0001".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceBasicRealTimehexedge01().toJSONString());
//                }
//                if("SimDeviceBasicGateway01".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceBasicRealTimeGateway01().toJSONString());
//                }
//                if("SimDeviceBasichexedge01".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceBasicRealTime4GGW0001().toJSONString());
//                }
//                //查询tsdb数据控中的仿真的数据(tag=name) hexedge01 Gateway01 4GGW0001
//                if("SimDeviceQualityhexedge01".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceQualityRealTimehexedge01().toJSONString());
//                }
//                if("SimDeviceQualityGateway01".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceQualityRealTimeGateway01().toJSONString());
//                }
//                if("SimDeviceQuality4GGW0001".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceQualityRealTime4GGW0001().toJSONString());
//                }
//                //查询模拟设备的粗节数据信息(tag=name)hexedge01 Gateway01 4GGW0001
//                if("SimDeviceSlub2Hhexedge01".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceSlub2HRealTime4GGW0001().toJSONString());
//                }
//                if("SimDeviceSlub2HGateway01".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceSlub2HRealTimeGateway01().toJSONString());
//                }
//                if("SimDeviceSlub2H4GGW0001".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceSlub2HRealTimehexedge01().toJSONString());
//                }
//
//
//                //查询模拟设备的波谱图信息
//                if("SimDeviceWavehexedge01".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceWaveRealTimehexedge01().toJSONString());
//                }
//                if("SimDeviceWaveGateway01".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceWaveRealTimeGateway01().toJSONString());
//                }
//                if("SimDeviceWave4GGW0001".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceWaveRealTime4GGW0001().toJSONString());
//                }
//                //查询模拟设备的产量信息 hexedge01 Gateway01 4GGW0001
//                if("SimDeviceProductionhexedge01".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceProductionRealTimehexedge01().toString());
//                }
//                if("SimDeviceProductionGateway01".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceProductionRealTimeGateway01().toString());
//                }
//                if("SimDeviceProduction4GGW0001".equals(item.sid)){
//                    item.sendMessage(tsdbRealTimeUpdateService.SimDeviceProductionRealTime4GGW0001().toString());
//                }
                if("SimDeviceProduction".equals(item.sid)){
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceProductionRealTime("name",item.simName).toString());
                }
                if("SimDeviceWave".equals(item.sid)){
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceWaveRealTime("name",item.simName).toString());
                }
                if("SimDeviceSlub2H".equals(item.sid)){
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceSlub2HRealTime("name",item.simName).toString());
                }
                if("SimDeviceBasic".equals(item.sid)){
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceBasicRealTime("name",item.simName).toString());
                }
                if("SimDeviceQuality".equals(item.sid)){
                    item.sendMessage(tsdbRealTimeUpdateService.DeviceQualityRealTime("name",item.simName).toString());
                }
                /*
                * 设备状态
                * */
                if ("DeviceStatus".equals(item.sid)){
                    item.sendMessage(JSON.toJSONString(getDeviceStatusResponseBodyDataList()));
                }

                //
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }

    /**
     * @ Param session
     * @ Param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public synchronized void sendMessage(String message) throws IOException {
//        log.info(message);
        this.session.getBasicRemote().sendText(message);
    }

    /**
   /*  * 群发自定义消息
     */
    /*
    public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
        log.info("推送消息到窗口" + sid + "，推送内容:" + message);

        for (RealTimeDataUpdateWebSocket item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的，为null则全部推送
                if (sid == null) {
//                    item.sendMessage(message);
                } else if (item.sid.equals(sid)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }*/

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        RealTimeDataUpdateWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        RealTimeDataUpdateWebSocket.onlineCount--;
    }

    public static CopyOnWriteArraySet<RealTimeDataUpdateWebSocket> getWebSocketSet() {
        return webSocketSet;
    }
}
